package com.jinwei.qunguanjia.web.monitor.controller;

import com.jinwei.qunguanjia.common.constant.CacheConstants;
import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.web.monitor.vo.SysCacheVO;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 缓存监控
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/cache")
public class CacheController
{
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PreAuthorize("@ss.hasPermission('monitor:cache:list')")
    @GetMapping()
    public Response getInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return Response.success(result);
    }

    @PreAuthorize("@ss.hasPermission('monitor:cache:list')")
    @GetMapping("/getNames")
    public Response cache()
    {
        List<SysCacheVO> caches = new ArrayList<>();
        caches.add(new SysCacheVO(String.format(CacheConstants.BACKEND_LOGIN_TOKEN_KEY), "用户信息"));
        caches.add(new SysCacheVO(String.format(CacheConstants.SYS_CONFIG_KEY), "配置信息"));
        caches.add(new SysCacheVO(String.format(CacheConstants.SYS_DICT_KEY), "数据字典"));
        caches.add(new SysCacheVO(String.format(CacheConstants.CAPTCHA_CODE_KEY), "验证码"));
        caches.add(new SysCacheVO(String.format(CacheConstants.REPEAT_SUBMIT_KEY), "防重提交"));
        caches.add(new SysCacheVO(String.format(CacheConstants.RATE_LIMIT_KEY), "限流处理"));
        return Response.success(caches);
    }

    @PreAuthorize("@ss.hasPermission('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public Response getCacheKeys(@PathVariable String cacheName)
    {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        return Response.success(cacheKeys);
    }

    @PreAuthorize("@ss.hasPermission('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public Response getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
    {
        String cacheValue = JsonUtils.toJsonString(redisTemplate.opsForValue().get(cacheKey));
        SysCacheVO sysCache = new SysCacheVO(cacheName, cacheKey, cacheValue);
        return Response.success(sysCache);
    }
}
